//
//  ViewController.m
//  数据存储方式(FMDB)
//
//  Created by whz on 17/2/28.
//  Copyright © 2017年 whz. All rights reserved.
//

#import "ViewController.h"
#import "Student.h"
#import "FMDBTools.h"

#define KMARGIN 10
#define KCELLID @"cellID"

@interface ViewController () <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>

@property(nonatomic, strong)UITextField *nameTextField;
@property(nonatomic, strong)UITextField *ageTextField;
@property(nonatomic, strong)UITextField *numberIdTextField;
@property(nonatomic, strong)UIButton *insertBtn;
@property(nonatomic, strong)UIButton *queryBtn;
@property(nonatomic, strong)UIButton *deleteBtn;
@property(nonatomic, strong)UIButton *updateBtn;
@property(nonatomic, strong)UIButton *saveBtn;
@property(nonatomic, strong)UISearchBar *searchBarView;
@property(nonatomic, strong)UITableView *showTableView;
@property(nonatomic, weak)UITableViewCell *cell;
@property(nonatomic, strong)NSMutableArray *modelArrayM;

@end

@implementation ViewController
{
    NSInteger _selectRow;
    Student *_stu;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupUI];
}

#pragma mark - FMDB_insert_delete_update_query

- (void)insertBtnClick:(UIButton *)sender {

    if (self.saveBtn.alpha == 1) {
        return;
    }
    
    if (self.nameTextField.text.length) {
        
        Student *stuModel = [Student modelWithId:0 Name:self.nameTextField.text age:self.ageTextField.text no:self.numberIdTextField.text];
        
        BOOL isInsert = [FMDBTools insertModel:stuModel];
        
        if (isInsert) {
            
            [self.modelArrayM addObject:stuModel];
//            [self.showTableView reloadData];
            [self clearTextField];
            NSLog(@"插入数据成功");
            
        } else {
            NSLog(@"插入数据失败");
        }
        [self queryBtnClick:nil];
    
    } else {
        
        [self showAlertWithDefaultAlertTitle:@"提示" alertMessage:@"至少写上名字" alertPreferredStyle:UIAlertControllerStyleAlert andActionTitleDefault:@"知道了" actionStyleDefault:UIAlertActionStyleDefault actionHandlerDefault:nil];
    }
    
}

- (void)queryBtnClick:(UIButton *)sender {

    if (self.saveBtn.alpha == 1) {
        return;
    }
    
    self.searchBarView.text = @"";
    
    if ([self.nameTextField.text  isEqual: @""] && [self.ageTextField.text  isEqual: @""] && [self.numberIdTextField.text  isEqual: @""]) {
        
        [self.modelArrayM removeAllObjects];
        NSArray *stuModel = [FMDBTools queryData:nil];
        [self.modelArrayM addObjectsFromArray:stuModel];
        [self clearTextField];
        [self.showTableView reloadData];
    }
}

- (void)updateBtnClick:(UIButton *)sender {

    self.saveBtn.alpha = 1;
}

- (void)deleteBtnClick:(UIButton *)sender {
    
    if (self.saveBtn.alpha == 1) {
        return;
    }
    
    if ([self.nameTextField.text  isEqual: @""] && [self.ageTextField.text  isEqual: @""] && [self.numberIdTextField.text  isEqual: @""]) {
        
        [self showAlertWithDefaultAlertTitle:@"提示" alertMessage:@"请输入你要查询人的姓名或者编号" alertPreferredStyle:UIAlertControllerStyleAlert andActionTitleDefault:@"确定" actionStyleDefault:UIAlertActionStyleDefault actionHandlerDefault:nil];
        
    } else {
        
        if (self.nameTextField.text || self.numberIdTextField.text) {
            
            // 如果选中的是第0行，需要做对象转换，否则不执行代码块
            if (![@(_selectRow) isEqual:@""]) {
                
                [FMDBTools deleteData:_stu.ID];
                [self showAlertWithDefaultAlertTitle:@"提示" alertMessage:@"删除成功" alertPreferredStyle:UIAlertControllerStyleAlert andActionTitleDefault:@"返回" actionStyleDefault:UIAlertActionStyleDefault actionHandlerDefault:nil];
                [self clearTextField];
                [self queryBtnClick:nil];
                
            } else {
                
                [self showAlertWithDefaultAlertTitle:@"提示" alertMessage:@"请选中你要删除的用户" alertPreferredStyle:UIAlertControllerStyleAlert andActionTitleDefault:@"确定" actionStyleDefault:UIAlertActionStyleDefault actionHandlerDefault:nil];
                
                return;
            }
        }
    }
    [self queryBtnClick:nil];
}

- (void)saveBtnClick:(UIButton *)sender {

    [self showAlertWithDefaultAndCancelAlertTitle:@"提示" alertMessage:@"是否要修改用户" alertPreferredStyle:UIAlertControllerStyleAlert andActionTitleDefault:@"我要修改" actionStyleDefault:UIAlertActionStyleDefault actionHandlerDefault:^(UIAlertAction * _Nonnull action) {
        
        _stu.name = self.nameTextField.text;
        _stu.age = self.ageTextField.text;
        _stu.numberId = self.numberIdTextField.text;
        
        [FMDBTools modifyData:_stu];
        [self queryBtnClick:nil];
        
        self.saveBtn.alpha = 0;
        [self queryBtnClick:nil];
        
    } andActionTitleCancel:@"我再想想" actionStyleCancel:UIAlertActionStyleDefault actionHandlerCancel:^(UIAlertAction * _Nonnull action) {
        
        self.saveBtn.alpha = 0;
    }];
}

#pragma mark - SearchBarDelegate

/**
 模糊查询
 */
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
    [self.modelArrayM removeAllObjects];
    
    NSString *fuzzyQuerySql = [NSString stringWithFormat:@"SELECT * FROM t_stuModel WHERE name LIKE '%%%@%%' OR numberId LIKE '%%%@%%'", searchText, searchText];
    NSArray *stuModel = [FMDBTools queryData:fuzzyQuerySql];
    
    [self.modelArrayM addObjectsFromArray:stuModel];
    
    [self.showTableView reloadData];
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    _selectRow = indexPath.row;
    _stu = self.modelArrayM[_selectRow];
    self.nameTextField.text = _stu.name;
    self.ageTextField.text = _stu.age;
    self.numberIdTextField.text = _stu.numberId;
}

#pragma mark - UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.modelArrayM.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:KCELLID forIndexPath:indexPath];
    self.cell = cell;
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:KCELLID];
    }
    Student *stuModel = self.modelArrayM[indexPath.row];
    cell.textLabel.text = stuModel.name;
    cell.detailTextLabel.text = stuModel.numberId;
    
    NSLog(@"%@--%@",stuModel.name,stuModel.numberId);
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 60;
}

#pragma mark - method

- (void)showAlertWithDefaultAndCancelAlertTitle:(NSString *)alertTitle alertMessage:(NSString *)alertMessage alertPreferredStyle:(UIAlertControllerStyle)alertStyle andActionTitleDefault:(NSString *)actionTitleDefault actionStyleDefault:(UIAlertActionStyle)actionStyleDefault actionHandlerDefault:(void (^) (UIAlertAction * _Nonnull))handlerDefault andActionTitleCancel:(NSString *)actionTitleCancel actionStyleCancel:(UIAlertActionStyle)actionStyleCancel actionHandlerCancel:(void (^) (UIAlertAction * _Nonnull))handlerCancel{
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:alertTitle message:alertMessage preferredStyle:alertStyle];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:actionTitleDefault style:actionStyleDefault handler:handlerDefault]];
    [alertVc addAction:[UIAlertAction actionWithTitle:actionTitleCancel style:actionStyleCancel handler:handlerCancel]];
    
    [self presentViewController:alertVc animated:YES completion:nil];
}

- (void)showAlertWithCancelAlertTitle:(NSString *)alertTitle alertMessage:(NSString *)alertMessage alertPreferredStyle:(UIAlertControllerStyle)alertStyle andActionTitleCancel:(NSString *)actionTitleCancel actionStyleCancel:(UIAlertActionStyle)actionStyleCancel actionHandlerCancel:(void (^) (UIAlertAction * _Nonnull))handlerCancel{

    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:alertTitle message:alertMessage preferredStyle:alertStyle];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:actionTitleCancel style:actionStyleCancel handler:handlerCancel]];

    [self presentViewController:alertVc animated:YES completion:nil];
}

- (void)showAlertWithDefaultAlertTitle:(NSString *)alertTitle alertMessage:(NSString *)alertMessage alertPreferredStyle:(UIAlertControllerStyle)alertStyle andActionTitleDefault:(NSString *)actionTitleDefault actionStyleDefault:(UIAlertActionStyle)actionStyleDefault actionHandlerDefault:(void (^) (UIAlertAction * _Nonnull))handlerDefault{
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:alertTitle message:alertMessage preferredStyle:alertStyle];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:actionTitleDefault style:actionStyleDefault handler:handlerDefault]];
    
    [self presentViewController:alertVc animated:YES completion:nil];
}

- (void)clearTextField {

    self.nameTextField.text = @"";
    self.ageTextField.text = @"";
    self.numberIdTextField.text = @"";
}

- (void)setupUI {

    [self.view addSubview:self.nameTextField];
    [self.view addSubview:self.ageTextField];
    [self.view addSubview:self.numberIdTextField];
    [self.view addSubview:self.insertBtn];
    [self.view addSubview:self.queryBtn];
    [self.view addSubview:self.deleteBtn];
    [self.view addSubview:self.updateBtn];
    [self.view addSubview:self.searchBarView];
    [self.view addSubview:self.showTableView];
    [self.view addSubview:self.saveBtn];
    
    if ((self.cell.textLabel.text = @"")) {
    
        [self queryBtnClick:nil];
    }
}

#pragma mark - lazyLoad

- (UISearchBar *)searchBarView {

    if (!_searchBarView) {
        
        _searchBarView = [[UISearchBar alloc] initWithFrame:CGRectMake(self.insertBtn.frame.origin.x, self.insertBtn.frame.origin.y+self.insertBtn.frame.size.height+KMARGIN, self.view.frame.size.width-2*KMARGIN, 30)];
        _searchBarView.delegate = self;
    }
    return _searchBarView;
}

- (UITableView *)showTableView {

    if (!_showTableView) {
        
        _showTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.searchBarView.frame.origin.x, self.searchBarView.frame.origin.y+self.searchBarView.frame.size.height+KMARGIN, self.view.frame.size.width-2*KMARGIN, self.view.frame.size.height-self.searchBarView.frame.origin.y-self.searchBarView.frame.size.height-2*KMARGIN)];
        _showTableView.delegate = self;
        _showTableView.dataSource = self;
        [_showTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:KCELLID];
        _showTableView.tableHeaderView = _searchBarView;
    }
    return _showTableView;
}

- (UITextField *)nameTextField {

    if (!_nameTextField) {
        
        _nameTextField = [[UITextField alloc] initWithFrame:CGRectMake(KMARGIN, 64, (self.view.frame.size.width-4*KMARGIN)/3, 30)];
        _nameTextField.textAlignment = NSTextAlignmentCenter;
        _nameTextField.placeholder = @"姓名";
        _nameTextField.borderStyle = UITextBorderStyleRoundedRect;
    }
    return _nameTextField;
}

- (UITextField *)ageTextField {
    
    if (!_ageTextField) {
        _ageTextField = [[UITextField alloc] initWithFrame:CGRectMake(2*KMARGIN+(self.view.frame.size.width-4*KMARGIN)/3, 64, (self.view.frame.size.width-4*KMARGIN)/3, 30)];
        _ageTextField.textAlignment = NSTextAlignmentCenter;
        _ageTextField.placeholder = @"年龄";
        _ageTextField.borderStyle = UITextBorderStyleRoundedRect;
    }
    return _ageTextField;
}

- (UITextField *)numberIdTextField {
    
    if (!_numberIdTextField) {
        
        _numberIdTextField = [[UITextField alloc] initWithFrame:CGRectMake(3*KMARGIN+(self.view.frame.size.width-4*KMARGIN)/3*2, 64, (self.view.frame.size.width-4*KMARGIN)/3, 30)];
        _numberIdTextField.textAlignment = NSTextAlignmentCenter;
        _numberIdTextField.placeholder = @"编号";
        _numberIdTextField.borderStyle = UITextBorderStyleRoundedRect;
    }
    return _numberIdTextField;
}

- (UIButton *)insertBtn {
    
    if (!_insertBtn) {
        
        _insertBtn = [[UIButton alloc] initWithFrame:CGRectMake(KMARGIN, 100, (self.view.frame.size.width-5*KMARGIN)/4, 30)];
        [_insertBtn setTitle:@"插入" forState:UIControlStateNormal];
        [_insertBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _insertBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        _insertBtn.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.1];
        [_insertBtn addTarget:self action:@selector(insertBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _insertBtn;
}

- (UIButton *)queryBtn {
    
    if (!_queryBtn) {
        
        _queryBtn = [[UIButton alloc] initWithFrame:CGRectMake(KMARGIN*2+(self.view.frame.size.width-5*KMARGIN)/4, 100, (self.view.frame.size.width-5*KMARGIN)/4, 30)];
        [_queryBtn setTitle:@"查询" forState:UIControlStateNormal];
        [_queryBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _queryBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        _queryBtn.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.1];
        [_queryBtn addTarget:self action:@selector(queryBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _queryBtn;
}

- (UIButton *)updateBtn {
    
    if (!_updateBtn) {
        
        _updateBtn = [[UIButton alloc] initWithFrame:CGRectMake(KMARGIN*3+2*(self.view.frame.size.width-5*KMARGIN)/4, 100, (self.view.frame.size.width-5*KMARGIN)/4, 30)];
        [_updateBtn setTitle:@"修改" forState:UIControlStateNormal];
        [_updateBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _updateBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        _updateBtn.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.1];
        [_updateBtn addTarget:self action:@selector(updateBtnClick:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _updateBtn;
}

- (UIButton *)deleteBtn {
    
    if (!_deleteBtn) {
        
        _deleteBtn = [[UIButton alloc] initWithFrame:CGRectMake(KMARGIN*4+3*(self.view.frame.size.width-5*KMARGIN)/4, 100, (self.view.frame.size.width-5*KMARGIN)/4, 30)];
        [_deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
        [_deleteBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _deleteBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        _deleteBtn.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.1];
        [_deleteBtn addTarget:self action:@selector(deleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _deleteBtn;
}

- (UIButton *)saveBtn {

    if (!_saveBtn) {
        
        _saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.center.x-self.insertBtn.frame.size.width*0.5, self.insertBtn.frame.origin.y+self.insertBtn.frame.size.height+KMARGIN, self.insertBtn.frame.size.width, self.insertBtn.frame.size.height)];
        [_saveBtn setTitle:@"是否保存" forState:UIControlStateNormal];
        [_saveBtn setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
        _saveBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        _saveBtn.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.1];
        [_saveBtn addTarget:self action:@selector(saveBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        _saveBtn.alpha = 0;
    }
    return _saveBtn;
}

- (NSMutableArray *)modelArrayM {

    if (!_modelArrayM) {
        
        _modelArrayM = [[NSMutableArray alloc] init];
    }
    return _modelArrayM;
}

@end
